<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/5/17
 * Time: 12:45
 */

namespace app\index\controller;

use app\common\controller\Frontend;
use think\config;
use fast\Tool;
use app\common\model\ChatMessage;
use app\common\model\VisitorMessage;

class Kf extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';


    private function deLoginToken($token){
        // 判断访问设备必须是微信浏览器，否则跳的微信的网页qq.com
        if(Config::get('xpz.kf_front_only_wx') ==1){
            $useragent = addslashes(request()->server('HTTP_USER_AGENT'));
            if(strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false ){
                echo "请在微信客户端打开！";
                exit;
            }
        }
        if(empty($token)){
            echo "非法登录，token不能为空！";exit;
        }
        $tokenRs = Tool::deLoginToken($token);
        if(!empty($tokenRs)){

            $userId = (int)$tokenRs[0];
            $openId = $tokenRs[1];
            $expireTime = (int)$tokenRs[2];
            if(empty($openId) || empty($userId) || empty($expireTime)){
                echo "登录参数不正确！";exit;
            }
            if($expireTime < time()){
                echo "登录超时！";exit;
            }
            $userInfo = model("User")->where(['id'=>$userId])->find();
            if(md5($userInfo['openid']) == $openId){
                if($userInfo['status'] == 'normal'){
                    return $userInfo;
                } else {
                    echo "此用户已被禁用！";exit;
                }

            }
        } else {
            echo "非法登录,token不正确！";exit;
        }
    }

    public function kf($uuid,$token){
        if(empty($uuid)){
            echo "请选择聊天对象！";exit;
        }
        $userInfo = $this->deLoginToken($token);

        $this->assign('uuid',$uuid);
        $this->assign('token',Tool::en_token($userInfo['id'],$userInfo['company_id']));
        $this->assign('config',Config::get('chat'));
        $this->assign('isHttps', Tool::is_https());
        $this->assign('domain', Tool::getDomain());
        $this->assign('token2',$token);
        return $this->view->fetch();
    }

    public function getRecord($token,$uuid,$page){
        if(empty($token)){
            echo "token不能为空！";exit;
        }
        if(empty($uuid)){
            echo "uuid不能为空！";exit;
        }
        if(empty($page)){
            $page = 1;
        }
//        $params = $this->request->param();
        $limit = 10;
        list($userId,$companyId) = Tool::de_token($token);
        $where = ['user_id'=>$userId,'uuid'=>$uuid,'company_id'=>$companyId];
        $message_list = model('ChatMessage')->where($where)->order('add_time desc')->paginate($limit, false, ['page' => $page]);
//        echo model('ChatMessage')->getLastSql();exit;
        if(!empty($message_list)){
            foreach($message_list as $key=>$val){
                if (date('m-d', strtotime('-1 day')) == date('m-d', $val['add_time'])) {
                    $message_list[$key]['time'] = '昨天 ' . date('H:i', $val['add_time']);
                } elseif (date('m-d') == date('m-d', $val['add_time'])) {
                    $message_list[$key]['time'] = date('H:i', $val['add_time']);
                } else {
                    $message_list[$key]['time'] = date('m-d', $val['add_time']) . ' ' . date('H:i', $val['add_time']);
                }
            }
        }
        $this->result($message_list, 1, '', 'json');

    }

    public function lists($token){
        if(empty($token)){
            echo "非法登录！";exit;
        }
        $this->assign('addon_config', Config::get('xpz'));
        $this->assign('isHttps', Tool::is_https());

//        $userInfo = OnlineServiceManage::getAdminByUserId($this->auth->id);
//        print_r($userInfo);exit;
        $userInfo = $this->deLoginToken($token);if(empty($userInfo['id'])){
            echo "该用户未绑定客服！";exit;
        }
        $list = ChatMessage::getVisitorList($userInfo['id'], $userInfo['company_id']);
        $this->assign('list', $list);
        $this->assign('token',$token);
        $this->assign('url',Tool::getDomain()."/kfchat");
        return $this->view->fetch('list');
    }

    public function liuyanList($token){
//        print_r($token);exit;
        if(empty($token)){
            echo "非法登录！";exit;
        }
        $userInfo = $this->deLoginToken($token);
        if(empty($userInfo['id'])){
            echo "该用户未绑定客服！";exit;
        }
        $list = VisitorMessage::getList($userInfo['id']);
        $this->assign('list', $list);
        $this->assign('token',$token);
        $this->assign('url',Tool::getDomain()."/visitorliuyan");
        return $this->view->fetch('liuyanlist');
    }

    public function liuyan($id,$token){
        if(empty($id)){
            echo "请选择要查看的留言！";exit;
        }
        if(empty($token)){
            echo "非法登录！";exit;
        }

        $userInfo = $this->deLoginToken($token);
//        print_r($userInfo);exit;
        if(empty($userInfo['id'])){
            echo "该用户未绑定客服！";exit;
        }
//        $this->assign('uuid',$uuid);
//        $this->assign('token',Tool::en_token($userInfo['admin_id'],1));
//        $this->assign('config',Config::get('online'));
//        $this->assign('isHttps', Tool::is_https());
        $this->assign('domain', Tool::getDomain());
        $this->assign('token2',$token);
//        echo $id;exit;
        $rs = VisitorMessage::getInfo($id);
//        var_dump($rs);exit;
        $this->assign('info',$rs);
        return $this->view->fetch();


    }

}